/*
	Copyright (c) 2010, Mathias Myrland, Myrland Systemutvikling (mathias@myrsys.no)
	All rights reserved.

	Redistribution and use in source and binary forms, with or without
	modification, are permitted provided that the following conditions are met:
	
	    * Redistributions of source code must retain the above copyright
	      notice, this list of conditions and the following disclaimer.
	      
	    * Redistributions in binary form must reproduce the above copyright
	      notice, this list of conditions and the following disclaimer in the
	      documentation and/or other materials provided with the distribution.
	      
	    * Neither the name of Myrland Systemutvikling nor the
	      names of its contributors may be used to endorse or promote products
	      derived from this software without specific prior written permission.

	THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
	ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
	WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
	DISCLAIMED. IN NO EVENT SHALL Myrland Systemutvikling BE LIABLE FOR ANY
	DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
	(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
	LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
	ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
	(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
	SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef CGF_MANAGED_CONTAINER_HPP
#define CGF_MANAGED_CONTAINER_HPP

#include <boost/unordered_set.hpp>
#include <boost/unordered_map.hpp>
#include <boost/weak_ptr.hpp>
#include <cgf/signal.hpp>
#include <cgf/object.hpp>
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <list>

namespace CGF
{	
	
	
	class MonitorTypes
	{
		public:
			enum type { NAMES, CLASSES };
	};
	
	/**
	*	A managed container class.
	*
	*	The t_stored type must be derived from SignalProducer
	*
	*	@tparam t_container		The type of the container to manage
	*	@tparam t_stored			The type of the pointers to store
	*	@tparam t_ptr			The kind of pointers to store	*/
	template<class t_stored, template<class> class t_container = std::list, template<class> class t_ptr = boost::weak_ptr >
	class ManagedContainer : public SignalProducer< ManagedContainer<t_stored, t_container, t_ptr > > 
	{
		typedef boost::weak_ptr<t_stored> ptr_w_stored;
		typedef boost::shared_ptr<t_stored> ptr_stored;
		typedef t_container<t_ptr<t_stored> > t_storage;
		
		/**	The actual container we are managing	*/
		t_storage m_contained;
		
		/**	Whether or not we maintain signal maps for classes	*/
		bool m_monitorClasses;
		/**	Whether or not we maintain signal maps for names	*/
		bool m_monitorNames;
		
		SignalProducer<t_stored> m_classSignals, m_nameSignals;
		
		//std::list<boost::signals::connection> connections
		boost::unordered_map<void*, boost::signals::connection> connections;
		
		template<template<class> class t_convPtr, class t_retType>
		class GetPointer
		{
			public: 
				t_retType* operator() ( const t_convPtr<t_retType> pointer )
				{
					return pointer.get();
				}
		};
		template<class t_retType>
		class GetPointer<boost::weak_ptr, t_retType>
		{
			public: 
				t_retType* operator() ( const boost::weak_ptr<t_retType> pointer )
				{
					return pointer.lock().get();
				}
		};
		
		public:
			
			typedef typename t_storage::iterator iterator;
		
			/**
			*	The onDestroyed notification slot. This function is connected to its managed objects destroyed signal.
			*
			*	@param	obj	The object being destroyed, which is to be removed from the container.	*/
			void onDestroyed ( ptr_stored obj )
			{
				connections.erase ( obj.get() );
				
				iterator it = m_contained.begin();
				for ( ; it != m_contained.end(); it++ )
				{
					if ( !(*it).use_count() )
						break;
				}
				m_contained.erase ( it );
			}
			
			/**
			*	Get the first created element matching the provided criteria
			*	@param	keyvalue		The key to match ( either the name or a class )
			*	@tparam	keytype		The type of the key (either MonitorTypes::CLASSES or NAMES)	*/
			template<MonitorTypes::type t_key>
			ptr_stored firstEntry ( std::string key )
			{
				//	Select the first matching element
				ManagedContainer<t_stored, t_container, t_ptr> mon;
				mon.monitor<ManagedContainer<t_stored, t_container, t_ptr>, t_key> ( this->_this().lock(), key, 1 );
				
				if ( mon.size() )
					return (*mon.begin()).lock();
				
				return ptr_stored();
			}
			
			size_t size()
			{
				return m_contained.size();
			}
			/**
			*	Return the begin iterator of the storage class
			*
			*	@return	iterator to the first element of the managed list	*/
			const iterator begin()
			{
				return m_contained.begin();
			}
			/**
			*	Return the end iterator of the storage class
			*
			*	@return	iterator to the last+1 element of the managed list	*/
			const iterator end()
			{
				return m_contained.end();
			}		
			
			void sort()
			{
				m_contained.sort();
			}
			iterator erase ( iterator pos )
			{
				//	Create a getter
				GetPointer<t_ptr, t_stored> getter;
				t_stored* pointer = getter ( (*pos) );
				
				//	Terminate this connection
				connections[ (void*)pointer].disconnect( );
				connections.erase ( (void*)pointer );
			
				return m_contained.erase ( pos );
			}
			
			void clear()
			{
				m_contained.clear();
			}
			
			void pop_front()
			{
				erase ( begin() );
			}
			
			/**
			*	Connects the provided function to another container and listens for new entries of the specified type
			*	@param	cont	The container to monitor
			*	@param	key	The name to monitor
			*	@param	limit	When limit it specified, the monitor function works like a limited query rather than a constant monitoring
			*	@tparam	t_cont	The type of the container we are monitoring
			*	@tparam	type	either moniotrype::NAMES or monitortypes::CLASSES	*/
			template<class t_cont, MonitorTypes::type type>
			void monitor ( boost::shared_ptr<t_cont> cont, std::string key, size_t limit = 0 )
			{
				//	We bind the push_bakc function to the signal
				boost::function<void(ptr_stored)> func = boost::bind ( &ManagedContainer<t_stored, t_container, t_ptr>::push_back, this, _1 );
				cont->listen<type> ( func, key, limit );
			}
			
			/**
			*	Connects the provided function to a signal map and listens for new entries of the specified type
			*	@param	callback	The callback function for the signal on the form boost::function<void (boost::shared_ptr<t_stored> )>
			*	@param	key	The name to monitor
			*	@tparam	t_cont	The type of the container
			*	@tparam	type	either moniotrype::NAMES or monitortypes::CLASSES	*/
			template<MonitorTypes::type type>
			void listen ( boost::function<void(ptr_stored)> func, std::string key, size_t limit = 0 )
			{
				size_t found = 0;
				iterator ent = m_contained.begin();
				for ( ; ent != m_contained.end(); ent++ )
				{
					if ( type == MonitorTypes::NAMES && (*ent).lock()->name() == key )
					{
						found++;
						func ( (*ent).lock() );
					}
					if ( type == MonitorTypes::CLASSES && (*ent).lock()->hasClass(key) )
					{
						found++;
						func ( (*ent).lock() );
					}
					
					if ( limit && found >= limit )
						return;
				}
				
				switch ( type )
				{
					case MonitorTypes::NAMES:
						m_nameSignals.connect ( key, func );
						m_monitorNames = true;
					break;
					case MonitorTypes::CLASSES:
						m_classSignals.connect ( key, func );
						m_monitorClasses = true;
					break;
				}
			}
			
			/**
			*	Pushes a value to the back of the container
			*
			*	@param	value	A shared pointer to the value to push	*/
			void push_back ( ptr_stored value )
			{
				m_contained.push_back ( t_ptr<t_stored> ( value ) );
				boost::function<void(ptr_stored)> func;
				func = boost::bind( &ManagedContainer<t_stored, t_container, t_ptr>::onDestroyed, this, _1 );
				connections[(void*)value.get()] = value->connect ( "destroyed",  func  );
			
				//	If we are monitoring class names 
				if ( m_monitorClasses )
				{
					boost::unordered_set<std::string>::iterator cls = value->classes().begin();
					for ( ; cls != value->classes().end(); cls++ )
					{
						//	Signal the listeners
						m_classSignals.signal ( (*cls), value );
					}
				}
				//	or just names names 
				if ( m_monitorNames)
				{
					//	Signal the listeners
					m_nameSignals.signal ( value->name(), value );
				}
				
				//	Signal the new entry slot
				this->signal ( "newEntry" );
			}
			
			ManagedContainer ()
			{
				m_monitorClasses = m_monitorNames = false;
			}
			
			~ManagedContainer()
			{
				boost::unordered_map<void*, boost::signals::connection>::iterator con = connections.begin();
				for ( ; con != connections.end(); con ++ )
					(*con).second.disconnect();
				clear();
			}
			
	};


}//	namespace CGF

#endif
